package com.witmore.neutron.ai.web.apiv2.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.PageInfo;
import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.jk.common.utils.PasswordUtil;
import com.witmore.neutron.ai.db.dto.UserWithProviderDTO;
import com.witmore.neutron.ai.db.entity.UserDO;
import com.witmore.neutron.ai.db.mapper.UserMapper;
import com.witmore.neutron.ai.web.annotation.RequiresPermission;
import com.witmore.neutron.ai.web.controller.vo.*;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * V2 用户管理接口
 * Author: 豆子高
 * Date: 2025/9/1
 */
@RestController
@RequestMapping("/v2/user")
public class UserManagementController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    /**
     * 用户列表查询（分页）
     * 使用联表查询解决服务商筛选分页问题
     */
    @RequiresPermission("user:list")
    @GetMapping("/list")
    public ResponsePageResult<UserListVO> getUserList(UserListQuery query) {
        // 使用自定义的联表查询方法
        Page<UserWithProviderDTO> page = new Page<>(query.getPage(), query.getSize());

        Page<UserWithProviderDTO> userWithProviderPage = userMapper.selectUserListWithProvider(
                page,
                query.getUserName(),
                query.getUserPhone(),
                query.getProviderName(),
                query.getActiveStatus()
        );

        if (userWithProviderPage.getRecords().isEmpty()) {
            return ResponsePageResult.success(new ArrayList<>(),
                    new PageInfo(query.getPage(), query.getSize(), 0L, 0L));
        }

        // 转换为VO
        List<UserListVO> userListVOs = userWithProviderPage.getRecords().stream()
                .map(this::convertToUserListVO)
                .collect(Collectors.toList());

        // 构建返回结果
        PageInfo pageInfo = new PageInfo(
                userWithProviderPage.getCurrent(),
                userWithProviderPage.getSize(),
                userWithProviderPage.getTotal(),
                userWithProviderPage.getPages()
        );

        return ResponsePageResult.success(userListVOs, pageInfo);
    }

    /**
     * 将 UserWithProviderDTO 转换为 UserListVO
     */
    private UserListVO convertToUserListVO(UserWithProviderDTO dto) {
        UserListVO vo = new UserListVO();
        BeanUtils.copyProperties(dto, vo);
        return vo;
    }

    /**
     * 用户启用/禁用
     */
    @RequiresPermission("user:status:update")
    @PostMapping("/updateStatus")
    @Transactional
    public ResponseResult<Void> updateUserStatus(@RequestBody UserStatusUpdateParam param) {
        // 校验参数
        if (param.getUserId() == null || param.getActiveStatus() == null) {
            return ResponseResult.fail(400, "参数不能为空");
        }

        // 查询用户信息
        UserDO user = userMapper.selectById(param.getUserId());
        if (user == null) {
            return ResponseResult.fail(404, "用户不存在");
        }

        // 超级管理员不能被禁用
        if (Boolean.TRUE.equals(user.getIsSuperAdmin()) && param.getActiveStatus() == 0) {
            return ResponseResult.fail(403, "超级管理员不能被禁用");
        }

        // 更新用户状态
        user.setActiveStatus(param.getActiveStatus());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);

        return ResponseResult.success();
    }

    /**
     * 用户会话次数充值/扣款
     */
    @RequiresPermission("user:recharge")
    @PostMapping("/recharge")
    @Transactional
    public ResponseResult<Void> rechargeUserSession(@RequestBody UserRechargeParam param) {
        // 校验参数
        if (param.getUserId() == null ||
                param.getOperationTimes() == null || param.getOperationTimes() <= 0 ||
                param.getOperationType() == null) {
            return ResponseResult.fail(400, "参数不正确");
        }

        // 校验操作类型
        if (param.getOperationType() != 1 && param.getOperationType() != 2) {
            return ResponseResult.fail(400, "操作类型不正确（1：充值；2：扣款）");
        }

        // 查询用户信息
        UserDO user = userMapper.selectById(param.getUserId());
        if (user == null) {
            return ResponseResult.fail(404, "用户不存在");
        }

        // 获取当前操作用户信息
        UserSession currentUser = GlobalAccountSession.getUserInfo();
        if (currentUser == null) {
            return ResponseResult.fail(401, "未登录");
        }

        // 记录操作前的次数
        Integer beforeRemainingTimes = user.getSessionRemainingTimes() != null ?
                user.getSessionRemainingTimes() : 0;

        int afterRemainingTimes;
        if (param.getOperationType() == 1) {
            // 充值操作
            afterRemainingTimes = beforeRemainingTimes + param.getOperationTimes();
        } else {
            // 扣款操作
            afterRemainingTimes = beforeRemainingTimes - param.getOperationTimes();
            // 扣款后不能为负数
            if (afterRemainingTimes < 0) {
                return ResponseResult.fail(400, "扣款次数超过用户剩余次数");
            }
        }

        // 更新用户剩余次数
        user.setSessionRemainingTimes(afterRemainingTimes);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);

        userService.createRechargeRecord(user, param.getOperationTimes(), param.getOperationDesc(), currentUser.getId(),
                currentUser.getUserName(), beforeRemainingTimes, afterRemainingTimes, param.getOperationType());
        return ResponseResult.success();
    }

    /**
     * 新增用户
     */
    @RequiresPermission("user:create")
    @PostMapping("/create")
    @Transactional
    public ResponseResult<UserSession> createUser(@RequestBody UserCreateParam param) {
        // 校验参数
        if (!StringUtils.hasText(param.getUserName())) {
            return ResponseResult.fail(400, "用户名不能为空");
        }

        // 如果提供了手机号，需要进行格式验证和重复性校验
        if (StringUtils.hasText(param.getUserPhone())) {
            // 简单的手机号格式验证
            if (!param.getUserPhone().matches("^1[3-9]\\d{9}$")) {
                return ResponseResult.fail(400, "手机号格式不正确");
            }

            // 检查手机号是否已存在
            UserDO existingUser = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
                    .eq(UserDO::getUserPhone, param.getUserPhone())
            );
            if (existingUser != null) {
                return ResponseResult.fail(409, "手机号已被使用");
            }
        }

        // 创建新用户对象
        UserDO newUser = new UserDO();
        newUser.setNickName("系统新增_" + param.getUserName());
        newUser.setUserName(param.getUserName());

        // 设置手机号（可选）
        if (StringUtils.hasText(param.getUserPhone())) {
            newUser.setUserPhone(param.getUserPhone());
        }

        // 设置密码，默认为123456
        String password = StringUtils.hasText(param.getPassword()) ? param.getPassword() : "123456";
        newUser.setPassword(PasswordUtil.hashPassword(password));

        // 设置组织名称，默认为"默认组织"
        String orgName = StringUtils.hasText(param.getOrgName()) ? param.getOrgName() : "默认组织";
        newUser.setOrgName(orgName);

        // 设置头像URL（可选）
        if (StringUtils.hasText(param.getAvatarUrl())) {
            newUser.setAvatarUrl(param.getAvatarUrl());
        }

        // 创建用户
        UserDO createdUser = userService.createNewUserNormal(newUser);
        if (createdUser == null) {
            return ResponseResult.fail(500, "用户创建失败");
        }

        return ResponseResult.success();
    }
}
